<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <el-card class="search-wrapper">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="商家名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商家名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="queryParams.phone"
            placeholder="请输入联系电话"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="入驻状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择入驻状态" clearable>
            <el-option label="待审核" value="pending" />
            <el-option label="已通过" value="approved" />
            <el-option label="已拒绝" value="rejected" />
            <el-option label="已冻结" value="frozen" />
          </el-select>
        </el-form-item>
        <el-form-item label="入驻时间" prop="dateRange">
          <el-date-picker
            v-model="queryParams.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <el-icon><Search /></el-icon>搜索
          </el-button>
          <el-button @click="resetQuery">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作按钮 -->
    <el-card class="table-wrapper">
      <template #header>
        <div class="card-header">
          <span>商家入驻列表</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleExport">
              <el-icon><Download /></el-icon>导出
            </el-button>
            <el-button type="success" @click="handleBatchApprove" :disabled="!selectedMerchants.length">
              <el-icon><Check /></el-icon>批量通过
            </el-button>
            <el-button type="danger" @click="handleBatchReject" :disabled="!selectedMerchants.length">
              <el-icon><Close /></el-icon>批量拒绝
            </el-button>
          </div>
        </div>
      </template>

      <!-- 表格 -->
      <el-table
        v-loading="loading"
        :data="merchantList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商家名称" prop="name" min-width="150" show-overflow-tooltip />
        <el-table-column label="联系人" prop="contact" width="120" />
        <el-table-column label="联系电话" prop="phone" width="120" />
        <el-table-column label="商家类型" prop="type" width="120">
          <template #default="{ row }">
            <el-tag :type="row.type === 'individual' ? 'success' : 'warning'">
              {{ row.type === 'individual' ? '个人商家' : '企业商家' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入驻状态" prop="status" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="入驻时间" prop="createTime" width="180" />
        <el-table-column label="审核时间" prop="auditTime" width="180" />
        <el-table-column label="操作" align="center" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleView(row)">
              <el-icon><View /></el-icon>查看
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="success" 
              link 
              @click="handleApprove(row)"
            >
              <el-icon><Check /></el-icon>通过
            </el-button>
            <el-button 
              v-if="row.status === 'pending'"
              type="danger" 
              link 
              @click="handleReject(row)"
            >
              <el-icon><Close /></el-icon>拒绝
            </el-button>
            <el-button 
              v-if="row.status === 'approved'"
              type="warning" 
              link 
              @click="handleFreeze(row)"
            >
              <el-icon><Lock /></el-icon>冻结
            </el-button>
            <el-button 
              v-if="row.status === 'frozen'"
              type="success" 
              link 
              @click="handleUnfreeze(row)"
            >
              <el-icon><Unlock /></el-icon>解冻
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 查看详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="商家入驻详情"
      width="800px"
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="商家名称">{{ currentMerchant.name }}</el-descriptions-item>
        <el-descriptions-item label="商家类型">
          {{ currentMerchant.type === 'individual' ? '个人商家' : '企业商家' }}
        </el-descriptions-item>
        <el-descriptions-item label="联系人">{{ currentMerchant.contact }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ currentMerchant.phone }}</el-descriptions-item>
        <el-descriptions-item label="电子邮箱">{{ currentMerchant.email }}</el-descriptions-item>
        <el-descriptions-item label="入驻状态">
          <el-tag :type="getStatusType(currentMerchant.status)">
            {{ getStatusLabel(currentMerchant.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="营业执照" :span="2">
          <el-image 
            v-if="currentMerchant.businessLicense"
            :src="currentMerchant.businessLicense"
            :preview-src-list="[currentMerchant.businessLicense]"
            fit="contain"
            style="width: 200px; height: 200px"
          />
        </el-descriptions-item>
        <el-descriptions-item label="身份证正面" :span="2">
          <el-image 
            v-if="currentMerchant.idCardFront"
            :src="currentMerchant.idCardFront"
            :preview-src-list="[currentMerchant.idCardFront]"
            fit="contain"
            style="width: 200px; height: 200px"
          />
        </el-descriptions-item>
        <el-descriptions-item label="身份证反面" :span="2">
          <el-image 
            v-if="currentMerchant.idCardBack"
            :src="currentMerchant.idCardBack"
            :preview-src-list="[currentMerchant.idCardBack]"
            fit="contain"
            style="width: 200px; height: 200px"
          />
        </el-descriptions-item>
        <el-descriptions-item label="店铺地址" :span="2">{{ currentMerchant.address }}</el-descriptions-item>
        <el-descriptions-item label="经营范围" :span="2">{{ currentMerchant.businessScope }}</el-descriptions-item>
        <el-descriptions-item label="入驻时间">{{ currentMerchant.createTime }}</el-descriptions-item>
        <el-descriptions-item label="审核时间">{{ currentMerchant.auditTime }}</el-descriptions-item>
        <el-descriptions-item label="审核备注" :span="2">{{ currentMerchant.auditRemark }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditType === 'approve' ? '通过审核' : '拒绝审核'"
      width="500px"
      append-to-body
    >
      <el-form
        ref="auditFormRef"
        :model="auditForm"
        :rules="auditRules"
        label-width="100px"
      >
        <el-form-item label="审核备注" prop="remark">
          <el-input
            v-model="auditForm.remark"
            type="textarea"
            :rows="4"
            :placeholder="auditType === 'approve' ? '请输入通过备注' : '请输入拒绝原因'"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAudit">确 定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Download,
  Check,
  Close,
  View,
  Lock,
  Unlock
} from '@element-plus/icons-vue'
import {
  getMerchantList,
  approveMerchant,
  rejectMerchant,
  freezeMerchant,
  unfreezeMerchant,
  exportMerchantList
} from '@/api/merchant'

// 查询参数
const queryParams = reactive({
  name: '',
  phone: '',
  status: '',
  dateRange: [],
  pageNum: 1,
  pageSize: 10
})

// 表格数据
const loading = ref(false)
const merchantList = ref([])
const total = ref(0)
const selectedMerchants = ref([])

// 对话框相关
const dialogVisible = ref(false)
const currentMerchant = ref({})

// 审核相关
const auditDialogVisible = ref(false)
const auditType = ref('approve')
const auditFormRef = ref(null)
const auditForm = reactive({
  id: '',
  remark: ''
})

// 审核表单验证规则
const auditRules = {
  remark: [
    { required: true, message: '请输入审核备注', trigger: 'blur' },
    { min: 2, max: 200, message: '长度在 2 到 200 个字符', trigger: 'blur' }
  ]
}

// 获取商家列表
const getList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantList({
      ...queryParams,
      startDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1]
    })
    merchantList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取商家列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.name = ''
  queryParams.phone = ''
  queryParams.status = ''
  queryParams.dateRange = []
  handleQuery()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedMerchants.value = selection
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    pending: 'info',
    approved: 'success',
    rejected: 'danger',
    frozen: 'warning'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝',
    frozen: '已冻结'
  }
  return statusMap[status] || status
}

// 查看详情
const handleView = (row) => {
  currentMerchant.value = row
  dialogVisible.value = true
}

// 通过审核
const handleApprove = (row) => {
  auditType.value = 'approve'
  auditForm.id = row.id
  auditForm.remark = ''
  auditDialogVisible.value = true
}

// 拒绝审核
const handleReject = (row) => {
  auditType.value = 'reject'
  auditForm.id = row.id
  auditForm.remark = ''
  auditDialogVisible.value = true
}

// 批量通过
const handleBatchApprove = async () => {
  if (!selectedMerchants.value.length) return
  
  try {
    await ElMessageBox.confirm(
      `确认通过选中的 ${selectedMerchants.value.length} 个商家入驻申请吗？`,
      '提示',
      {
        type: 'warning'
      }
    )
    
    const ids = selectedMerchants.value.map(item => item.id)
    await Promise.all(ids.map(id => approveMerchant(id, { remark: '批量审核通过' })))
    ElMessage.success('批量通过成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量通过失败:', error)
    }
  }
}

// 批量拒绝
const handleBatchReject = async () => {
  if (!selectedMerchants.value.length) return
  
  try {
    await ElMessageBox.confirm(
      `确认拒绝选中的 ${selectedMerchants.value.length} 个商家入驻申请吗？`,
      '提示',
      {
        type: 'warning'
      }
    )
    
    const ids = selectedMerchants.value.map(item => item.id)
    await Promise.all(ids.map(id => rejectMerchant(id, { remark: '批量审核拒绝' })))
    ElMessage.success('批量拒绝成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量拒绝失败:', error)
    }
  }
}

// 冻结商家
const handleFreeze = async (row) => {
  try {
    await ElMessageBox.confirm('确认冻结该商家账号吗？', '提示', {
      type: 'warning'
    })
    await freezeMerchant(row.id, { remark: '商家账号冻结' })
    ElMessage.success('冻结成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('冻结商家失败:', error)
    }
  }
}

// 解冻商家
const handleUnfreeze = async (row) => {
  try {
    await ElMessageBox.confirm('确认解冻该商家账号吗？', '提示', {
      type: 'warning'
    })
    await unfreezeMerchant(row.id, { remark: '商家账号解冻' })
    ElMessage.success('解冻成功')
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('解冻商家失败:', error)
    }
  }
}

// 提交审核
const submitAudit = async () => {
  if (!auditFormRef.value) return
  
  try {
    await auditFormRef.value.validate()
    if (auditType.value === 'approve') {
      await approveMerchant(auditForm.id, { remark: auditForm.remark })
      ElMessage.success('审核通过成功')
    } else {
      await rejectMerchant(auditForm.id, { remark: auditForm.remark })
      ElMessage.success('审核拒绝成功')
    }
    auditDialogVisible.value = false
    getList()
  } catch (error) {
    console.error('提交审核失败:', error)
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...queryParams,
      startDate: queryParams.dateRange?.[0],
      endDate: queryParams.dateRange?.[1]
    }
    await exportMerchantList(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

// 分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  getList()
}

// 页码变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  getList()
}

onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;
  
  .search-wrapper {
    margin-bottom: 20px;
  }
  
  .table-wrapper {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-actions {
        display: flex;
        gap: 10px;
      }
    }
    
    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}
</style> 